﻿using System.Data.SqlClient;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace PritunlApiServer.Controllers
{
    public class UserController : ApiControllerBase
    {
        [AllowAnonymous]
        [HttpPost("login")]
        public IActionResult Login([FromBody] LoginUser user)
        {
            var sql = @"select UserId,UserName from UserInfo where UserId=@userid and PassWd=@passwd";

            var table = Sqldb.maindb.FromSql(sql).AddParameter(new SqlParameter("@userid", user.UserId)).AddParameter(new SqlParameter("@passwd", user.Passwd)).ToDataTable();

            if (table.Rows.Count != 1)
            {
                return new BadRequestResult();
            }

            // token
            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {
                { "UserId", user.UserId }, // 存储Id
                { "Account", table.Rows[0]["UserName"] }, // 存储用户名
            });


            // 获取刷新 token
            var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 43200); // 第二个参数是刷新 token 的有效期（分钟），默认三十天


            // 设置响应报文头
            Response.Headers["access-token"] = accessToken;
            Response.Headers["x-access-token"] = refreshToken;

            return new OkResult();
        }

        [HttpPost("teststr")]
        public ActionResult<string> GetStr()
        {
            return DateTime.Now.ToString("yyyy-MM-dd");
        }
    }
}